<template>
  <div class="register-container">
    <!-- 注册框主体 -->
    <div class="login-box">
      <div class="login-logo">
        <h3>用户注册</h3>
      </div>

      <!-- 注册表单 -->
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="80px">
        <!-- 邮箱输入框 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" prefix-icon="el-icon-user" clearable></el-input>
        </el-form-item>

        <!-- 用户名输入框 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" prefix-icon="el-icon-user" clearable></el-input>
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="registerForm.password"
              prefix-icon="el-icon-lock"
              type="password"
              show-password
          ></el-input>
        </el-form-item>

        <!-- 确认密码输入框 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              prefix-icon="el-icon-lock"
              type="password"
              show-password
          ></el-input>
        </el-form-item>

        <!-- 错误消息显示区域 -->
        <div class="message-container">
          <div v-if="registerError" class="error-message">{{ registerError }}</div>
          <div v-else class="empty-message-placeholder"></div>
        </div>

        <!-- 注册按钮 -->
        <div class="login-button1">
          <el-form-item>
            <el-button
                type="primary"
                @click="handleRegister"
                :loading="loading"
                class="login-button2"
            >注册</el-button>
          </el-form-item>
        </div>

        <!-- 切换到登录页面的链接 -->
        <div class="login-link">
          <span>已有账号？</span>
          <router-link to="/login" class="login-link-text">立即登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import service from '@/utils/request'
export default {
  name: 'Register',
  data() {
    return {
      // 注册表单数据
      registerForm: {
        email: '',
        username: '',
        password: '',
        confirmPassword: ''
      },
      // 注册错误消息
      registerError: '',
      // 表单验证规则
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
          { min: 5, max: 50, message: '邮箱长度在 5 到 50 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 30, message: '密码长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ]
      },
      // 注册按钮加载状态
      loading: false
    }
  },
  methods: {
    /*
     * 验证两次输入的密码是否一致
     */
    validatePassword(rule, value, callback) {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },

    /*
     * 处理注册表单提交
     */
    async handleRegister() {
      try {
        // 验证表单
        const isValid = await this.validateForm()
        if (!isValid) return

        // 显示加载状态
        this.loading = true
        this.registerError = ''

        // 后端
        const response = await service.post('/register', this.registerForm)
        //前端测试
        //const response = await service.get('/register')
        // 2. 检查响应是否为数组，并获取第一个元素
        const registerResult = Array.isArray(response.data) ? response.data[0] : response.data;
        if (registerResult.code === 10004) {
          // 注册成功
          this.$message.success(registerResult.msg)
          this.$router.push('/login')
        } else if (registerResult.code === 10003 || registerResult.code ===10002 ) {
          // 注册失败（邮箱已注册或用户名重复）
          this.registerError = registerResult.msg
        } else {
          // 其他错误情况
          throw new Error(registerResult.msg || '注册失败，请稍后重试')
        }
      } catch (error) {
        this.handleRegisterError(error)
      } finally {
        this.loading = false
      }
    },

    /*
     * 验证表单数据
     */
    validateForm() {
      return new Promise(resolve => {
        this.$refs.registerFormRef.validate(resolve)
      })
    },
    /*
     * 处理注册错误
     */
    handleRegisterError(error) {
      console.error('注册错误:', error)

      // 显示友好的错误消息
      if (error.response && error.response.data && error.response.data.message) {
        this.registerError = error.response.data.message
      } else if (error.message) {
        this.registerError = error.message
      } else {
        this.registerError = '注册失败，请稍后重试'
      }
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.login-box {
  width: 360px;
  padding: 30px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.login-logo {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo h3 {
  padding-left: 60px;
  color: #409eff;
  font-weight: 500;
}

.message-container {
  min-height: 20px;
  padding-left: 80px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
}

.empty-message-placeholder {
  height: 20px;
  visibility: hidden;
}

.login-button1 {
  margin-top: 10px;
  margin-left: 40px;
}

.login-button2 {
  width: 100%;
  max-width: 200px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.login-link-text {
  color: #409eff;
  text-decoration: none;
}

.login-link-text:hover {
  text-decoration: underline;
}
</style>